﻿using System;
using System.IO;
using System.Text;
using System.Threading;

using DreamCube.Foundation.Basic.Utility;

namespace RecoverImgPath
{
    class Program
    {
        private static Timer timer = null;
        private static Boolean done = false;

        static void Main(String[] args)
        {
            (new Action(() =>
            {
                try
                {
                    System.Threading.Thread.Sleep(1000);
                    DoRecoverImagePath();
                }
                catch (Exception ex)
                {
                    MyLog.MakeLog(ex);
                }
                done = true;
                Console.WriteLine("");
                Console.WriteLine("修复成功！按任何键退出...");
            })).BeginInvoke(null, null);

            Console.Write("正在修复...");
            timer = new Timer(new TimerCallback((o) =>
            {
                if (!done)
                {
                    Console.Write(".");
                    timer.Change(1500, Timeout.Infinite);
                }
            }), null, 1500, Timeout.Infinite);

            Console.Read();
        }

        /// <summary>
        /// 执行修复操作
        /// </summary>
        public static void DoRecoverImagePath()
        {
            String appPath = MyPath.BaseDirectory;
            String[] csvFiles = null;
            if (MyIO.TryGetFiles(appPath, out csvFiles, "*.csv", System.IO.SearchOption.TopDirectoryOnly))
            {
                for (Int32 i = 0; i < csvFiles.Length; i++)
                {
                    String text = MyIO.ReadText(csvFiles[i], Encoding.UTF8);
                    //csv文件名
                    String fileName = MyString.RightOfLast(csvFiles[i], "\\");
                    //不带缀名的文件名
                    String fileNameWithoutExtension = MyString.LeftOfLast(fileName, ".");
                    String imgPathName = Path.Combine(appPath, fileNameWithoutExtension);
                    String[] imgSrc = MyString.SubStringBetweenStr(text, "<IMG", ">", false, true);
                    if (imgSrc != null && imgSrc.Length > 0)
                    {
                        for (Int32 j = 0; j < imgSrc.Length; j++) 
                        {
                            String[] imgSrcValue = MyString.SubStringBetweenStr(imgSrc[j], "src=\"\"", "\"\"", false, true);
                            if (imgSrcValue != null && imgSrcValue.Length > 0)
                            {
                                //图片名
                                String imgName = MyString.RightOfLast(imgSrcValue[0], "\\");
                                String imageNewSrcValue ="FILE:///" + Path.Combine(imgPathName, imgName);
                                text = text.Replace(imgSrcValue[0], imageNewSrcValue);
                            }
                        }
                    }
                    MyIO.Write(csvFiles[i], text, false);
                }
            }
        }
    }
}
